package cn.mumzone.pos.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.event.InOrOutStockEvent;
import cn.mumzone.pos.model.RepoGoodsEntity;
import cn.mumzone.pos.model.RepoListGoodsEntity;
import cn.mumzone.pos.model.RepositoryEntity;
import cn.mumzone.pos.presenter.StockOutSearchPresenter;
import cn.mumzone.pos.presenter.contract.StockOutSearchContract;
import cn.mumzone.pos.ui.adapter.ADA_CustomStockIn;
import cn.mumzone.pos.ui.adapter.ADA_StockInAndOut;
import cn.mumzone.pos.ui.fragment.FRA_StockIn;
import cn.mumzone.pos.ui.fragment.FRA_StockOut;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener;
import cn.mumzone.pos.util.StockBatchHolder;

/**
 * Created by JoeLjt on 2019/10/8.
 * Email: lijiateng1219@gmail.com
 * Description:
 * <p>
 * 出库手动搜索页面
 * 搜索后操作数量，在数量监听中将结果通过 RxBus 实时发送给 {@link cn.mumzone.pos.ui.fragment.FRA_StockOut}
 */
public class ACT_SearchStockInOrOutForScan extends BaseActivity<StockOutSearchPresenter> implements StockOutSearchContract.View {

    public static final String KEY_SELECTED_REPO = "key_selected_repo";
    public static final String KEY_LOCAL_LIST = "key_local_list";

    public static final String KEY_SCAN_CODE = "key_scan_code";
    public static final String KEY_SCAN_LIST = "key_scan_list";

    public static final String KEY_STOCK_TYPE = "key_stock_type";
    public static final String KEY_IS_OTHER_TYPE = "key_is_other_type";

    @BindView(R.id.ll_empty_cart)
    LinearLayout llEmpty;
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;
    @BindView(R.id.rv_cart_goods)
    LRecyclerView rvCart;
    @BindView(R.id.et_scan)
    EditText etScan;
    @BindView(R.id.tv_select_count)
    TextView tvSelectCount;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;

    private RepositoryEntity mSelectedRepo;

    private LRecyclerViewAdapter mCommonGoodsViewAdapter;
    private ADA_StockInAndOut mCommonStockCartAdapter;

    private LRecyclerViewAdapter mCustomGoodsViewAdapter;
    private ADA_CustomStockIn mCustomStockCartAdapter;

    private String scanCode;
    private List<RepoListGoodsEntity> scanResult;
    private List<RepoListGoodsEntity> localCartList;
    private List<RepoListGoodsEntity> mSelectedData;

    private boolean isScanExecuted = false;

    private boolean isOtherType;

    private int stockType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        overridePendingTransition(R.anim.right_in, R.anim.right_out);
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.gravity = Gravity.END;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(params);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        setFinishOnTouchOutside(true);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        mSelectedRepo = (RepositoryEntity) extras.getSerializable(KEY_SELECTED_REPO);
        localCartList = (List<RepoListGoodsEntity>) extras.getSerializable(KEY_LOCAL_LIST);
        scanCode = extras.getString(KEY_SCAN_CODE, null);
        scanResult = (List<RepoListGoodsEntity>) extras.getSerializable(KEY_SCAN_LIST);
        stockType = extras.getInt(KEY_STOCK_TYPE);
        isOtherType = extras.getBoolean(KEY_IS_OTHER_TYPE, false);
    }

    @Override
    protected void initEventAndData() {

        initSearchCartRv();

        updateStockSearchResultUI(false);

        updateListAccordingToLocalCart(scanResult);

        if (isOtherType) {
            mCustomStockCartAdapter.update(scanResult, true);
            tvSelectCount.setText(String.valueOf(mCustomStockCartAdapter.getSelectedCount()));
            tvConfirm.setEnabled(mCustomStockCartAdapter.getSelectedCount() > 0);
        } else {
            mCommonStockCartAdapter.update(scanResult, true);
            tvSelectCount.setText(String.valueOf(mCommonStockCartAdapter.getSelectedCount()));
            tvConfirm.setEnabled(mCommonStockCartAdapter.getSelectedCount() > 0);
        }

    }

    private void updateStockSearchResultUI(boolean showDefault) {
        llEmpty.setVisibility(showDefault ? View.VISIBLE : View.GONE);
        rvCart.setVisibility(!showDefault ? View.VISIBLE : View.GONE);
    }

    private void initSearchCartRv() {

        tvConfirm.setText(stockType == FRA_StockIn.STOCK_TYPE_IN ? "加入入库" : "加入出库");

        rvCart.setLayoutManager(new LinearLayoutManager(mContext));

        initAdapterForCommon();
        initAdapterForCustom();

        rvCart.setAdapter(isOtherType ? mCustomGoodsViewAdapter : mCommonGoodsViewAdapter);
        rvCart.setPullRefreshEnabled(false);
        rvCart.setLoadMoreEnabled(false);

        etScan.setInputType(InputType.TYPE_NULL);
        EditTextUtil.hideSoftInputMethod(mContext, etScan);
        etScan.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    scanCode = code;

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.loadRepoGoodsByIdFromScan(mSelectedRepo != null ? StringUtils.get(mSelectedRepo.getId()) : "",
                                scanCode, false, true, getSearchTypeAccordingToStockType());
                        rvCart.setNoMore(false);
                    }
                    isScanExecuted = true;
                    etScan.setText("");
                }
                return true;
            }
        });

    }

    private String getSearchTypeAccordingToStockType() {
        if (stockType == FRA_StockIn.STOCK_TYPE_IN) {
            return isOtherType ? "1" : "2";
        }
        return "0";
    }

    private void initAdapterForCommon() {
        mCommonStockCartAdapter = new ADA_StockInAndOut(this, stockType, false);
        mCommonGoodsViewAdapter = new LRecyclerViewAdapter(mCommonStockCartAdapter);
        mCommonStockCartAdapter.setOnAmountChangeListener(new ADA_StockInAndOut.OnAmountChangeListener() {
            @Override
            public void onAmountChanged(int count, int tag, RepoListGoodsEntity entity) {
                // v2.3 取消搜索页与结果页实时交互，添加确认按钮
                tvSelectCount.setText(String.valueOf(mCommonStockCartAdapter.getSelectedCount()));
                tvConfirm.setEnabled(mCommonStockCartAdapter.getSelectedCount() > 0);
            }
        });
    }

    private void initAdapterForCustom() {
        mCustomStockCartAdapter = new ADA_CustomStockIn(this, false);
        mCustomGoodsViewAdapter = new LRecyclerViewAdapter(mCustomStockCartAdapter);
        mCustomStockCartAdapter.setOnAmountChangeListener(new ADA_CustomStockIn.OnAmountChangeListener() {
            @Override
            public void onAmountChanged(int count, int tag, RepoListGoodsEntity entity) {
                // v2.3 取消搜索页与结果页实时交互，添加确认按钮
                tvSelectCount.setText(String.valueOf(mCustomStockCartAdapter.getSelectedCount()));
                tvConfirm.setEnabled(mCustomStockCartAdapter.getSelectedCount() > 0);
            }
        });

        mCustomStockCartAdapter.setOnModifyBatchListener(new ADA_CustomStockIn.OnModifyBatchListener() {
            @Override
            public void onModifyBatch(RepoListGoodsEntity goodsEntity, RepoGoodsEntity batchInfo) {
                StockBatchHolder.INSTANCE.setTargetBean(goodsEntity);
                StockBatchHolder.INSTANCE.setTargetBatchBean(batchInfo);
                if (batchInfo != null) {
                    ACT_AddOrModifyBatch.startActForUpdate(mContext);
                } else {
                    ACT_AddOrModifyBatch.startActForAdd(mContext);
                }
            }
        });

    }

    @Override
    protected int getLayout() {
        return R.layout.act_search_stock_out_for_scan;
    }

    @Override
    protected View getTargetView() {
        return llGoods;
    }

    @OnClick({R.id.iv_finish, R.id.tv_confirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_finish:
                finish();
                overridePendingTransition(R.anim.right_in, R.anim.right_out);
                break;
            case R.id.tv_confirm:
                confirmAddCart();
                break;
        }
    }

    private void confirmAddCart() {
        if (isOtherType) {
            mSelectedData = mCustomStockCartAdapter.getSelectedData();
            RxBus.getDefault().post(new InOrOutStockEvent(mCustomStockCartAdapter.getDataList()));
            mCustomStockCartAdapter.clear();
        } else {
            mSelectedData = mCommonStockCartAdapter.getSelectedData();
            RxBus.getDefault().post(new InOrOutStockEvent(mCommonStockCartAdapter.getDataList()));
            mCommonStockCartAdapter.clear();
        }

        tvSelectCount.setText("0");
        tvConfirm.setEnabled(false);
        updateStockSearchResultUI(true);
        PosToast.INSTANCE.makeCheckMarkToast(mContext, String.format("已%s~", tvConfirm.getText().toString()));

        finish();
        overridePendingTransition(R.anim.right_in, R.anim.right_out);
    }

    public static void startActForScanFromStockOut(Activity activity, RepositoryEntity selectedRepo,
                                                   String scanCode, List<RepoListGoodsEntity> scanResult, LinkedList<RepoListGoodsEntity> localList) {
        Intent intent = new Intent(activity, ACT_SearchStockInOrOutForScan.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_SELECTED_REPO, selectedRepo);
        bundle.putSerializable(KEY_LOCAL_LIST, localList);
        bundle.putString(KEY_SCAN_CODE, scanCode);
        bundle.putSerializable(KEY_SCAN_LIST, (Serializable) scanResult);
        bundle.putInt(KEY_STOCK_TYPE, FRA_StockOut.STOCK_TYPE_OUT);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    public static void startActForScanFromStockIn(Activity activity, boolean isOtherType, RepositoryEntity selectedRepo,
                                                  String scanCode, List<RepoListGoodsEntity> scanResult, LinkedList<RepoListGoodsEntity> localList) {
        Intent intent = new Intent(activity, ACT_SearchStockInOrOutForScan.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_SELECTED_REPO, selectedRepo);
        bundle.putSerializable(KEY_LOCAL_LIST, localList);
        bundle.putString(KEY_SCAN_CODE, scanCode);
        bundle.putSerializable(KEY_SCAN_LIST, (Serializable) scanResult);
        bundle.putInt(KEY_STOCK_TYPE, FRA_StockIn.STOCK_TYPE_IN);
        bundle.putBoolean(KEY_IS_OTHER_TYPE, isOtherType);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    public void showGoodsList(List<RepoListGoodsEntity> goodsEntities, boolean isRefresh) {
        isScanExecuted = false;

        rvCart.refreshComplete(AppConstants.PAGE_SIZE);
        if (ListUtil.isListEmpty(goodsEntities)) {
            rvCart.setNoMore(true);
        }

        updateListAccordingToLocalCart(goodsEntities);

        updateDataByType(goodsEntities, isRefresh);

    }

    private void updateDataByType(List<RepoListGoodsEntity> goodsEntities, boolean isRefresh) {

        if (isOtherType) {
            mCustomStockCartAdapter.update(goodsEntities, isRefresh);
            if (isRefresh) {
                rvCart.setAdapter(mCustomGoodsViewAdapter);
            } else {
                mCustomGoodsViewAdapter.notifyDataSetChanged();
            }

            tvSelectCount.setText(String.valueOf(mCustomStockCartAdapter.getSelectedCount()));
            tvConfirm.setEnabled(mCustomStockCartAdapter.getSelectedCount() > 0);

            updateStockSearchResultUI(ListUtil.isListEmpty(mCustomStockCartAdapter.getDataList()));

            if (ListUtil.isListEmpty(mCustomStockCartAdapter.getDataList())) {
                toggleShowEmpty(true, R.mipmap.ic_bill_empty, "未搜索到商品", "");
            } else {
                toggleShowEmpty(false);
            }
        } else {
            mCommonStockCartAdapter.update(goodsEntities, isRefresh);
            if (isRefresh) {
                rvCart.setAdapter(mCommonGoodsViewAdapter);
            } else {
                mCommonGoodsViewAdapter.notifyDataSetChanged();
            }

            tvSelectCount.setText(String.valueOf(mCommonStockCartAdapter.getSelectedCount()));
            tvConfirm.setEnabled(mCommonStockCartAdapter.getSelectedCount() > 0);

            updateStockSearchResultUI(ListUtil.isListEmpty(mCommonStockCartAdapter.getDataList()));

            if (ListUtil.isListEmpty(mCommonStockCartAdapter.getDataList())) {
                toggleShowEmpty(true, R.mipmap.ic_bill_empty, "未搜索到商品", "");
            } else {
                toggleShowEmpty(false);
            }
        }

    }

    private void updateListAccordingToLocalCart(List<RepoListGoodsEntity> requestedList) {

        List<RepoListGoodsEntity> targetList = null;
        if (!ListUtil.isListEmpty(mSelectedData)) {
            targetList = mSelectedData;
        } else if (!ListUtil.isListEmpty(localCartList)) {
            targetList = localCartList;
        }

        if (!ListUtil.isListEmpty(targetList)) {
            for (RepoListGoodsEntity requestedEntity : requestedList) {
                for (RepoListGoodsEntity localEntity : targetList) {
                    if (localEntity.getGoodsId().equals(requestedEntity.getGoodsId())) {
                        if (localEntity.getIsBatch() == RepoListGoodsEntity.BATCH_OFF) {
                            requestedEntity.setSelectedCount(localEntity.getSelectedCount());

                            RepoGoodsEntity localBatchInfo = localEntity.getGoodsBatch().get(0);
                            RepoGoodsEntity requestAddBatchInfo = requestedEntity.getGoodsBatch().get(0);

                            requestedEntity.setSelectedCount(localEntity.getSelectedCount());
                            requestAddBatchInfo.setInStockPrice(localBatchInfo.getInStockPrice());
                        } else {

                            // 多批次商品，匹配批次号，设置已选值
                            for (RepoGoodsEntity localBatch : localEntity.getGoodsBatch()) {

                                // 舍弃非手动添加的批次
                                if (!localBatch.isManuallyAdd()) {
                                    continue;
                                }

                                // 带入入库列表的批次信息做展示
                                requestedEntity.getGoodsBatch().add(localBatch);

                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void showError(String msg) {
        if ("无此商品".equals(msg)) {
            updateStockSearchResultUI(false);
            toggleShowEmpty(true, R.mipmap.ic_bill_empty, "未搜索到商品", "");
        } else {
            super.showError(msg);
        }
        isScanExecuted = false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            if (isOtherType) {
                mCustomStockCartAdapter.notifyDataSetChanged();
                tvSelectCount.setText(String.valueOf(mCustomStockCartAdapter.getSelectedCount()));
            } else {
                mCommonStockCartAdapter.notifyDataSetChanged();
                tvSelectCount.setText(String.valueOf(mCommonStockCartAdapter.getSelectedCount()));
            }

            tvConfirm.setEnabled(true);
        }
    }

}
